package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.*;
import com.baidu.mapapi.utils.DistanceUtil;
import com.lzx.iteam.adapter.LegworkAddressListAdapter;
import com.lzx.iteam.bean.AddressData;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.StringUtil;

import java.util.ArrayList;


/**
 * Created by Megan on 16/4/13.
 */
public class LegworkMapSearchActivity extends Activity implements
        OnGetPoiSearchResultListener, View.OnClickListener, AbsListView.OnScrollListener {

    private EditText mEtSearch;
    private TextView mTvCancle;
    private ListView mLvList;
    private PoiSearch mPoiSearch = null;
    private LegworkAddressListAdapter mAdapter;
    private double mLongitude;
    private double mLatitude;
    private ArrayList<AddressData> mAddressDatas = new ArrayList<AddressData>();
    private Dialog mProgressDialog;

    private String searchText;
    private int pageIndex = 1;      // 加载的页数
    private int pageSize = 20;
    private TextView mFooterText;
    private LinearLayout mFooterLayout;
    private ProgressBar mFooterProgress;
    boolean is_scrolling = false;   // 是否还在滚动
    private int count;
    private String mGroupId;
    private String mFormId;
    private int flag;//0:普通  1:更新
    private String Tag = "LegworkMapSearchActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baidu_map_search_layout);
        initViews();
        getIntentData();
    }


    private void initViews() {

        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        mTvCancle = (TextView) findViewById(R.id.tv_map_search_input_cancle);
        mEtSearch = (EditText) findViewById(R.id.et_map_search_input);
        mLvList = (ListView) findViewById(R.id.lv_baidu_map_search_list);
        View footerView = LayoutInflater.from(LegworkMapSearchActivity.this).inflate(R.layout.xlistview_footer, null);
        mFooterLayout = (LinearLayout) footerView.findViewById(R.id.xlistview_footer_content);
        mFooterText = (TextView) footerView.findViewById(R.id.xlistview_footer_hint_textview);
        mFooterProgress = (ProgressBar) footerView.findViewById(R.id.xlistview_footer_progressbar);
        mFooterLayout.setVisibility(View.GONE);
        mLvList.addFooterView(footerView);
        mAdapter = new LegworkAddressListAdapter(this);
        mLvList.setAdapter(mAdapter);
        mLvList.setOnScrollListener(this);

        mLvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
               // Toast.makeText(LegworkMapSearchActivity.this, "选择的地址是:" + mAddressDatas.get(position).getAddress(), Toast.LENGTH_LONG).show();
                if (position == mAdapter.getCount()) {
                    return;
                } else {
                    if (flag == 0) {
                        Intent intent = new Intent(LegworkMapSearchActivity.this, LegworkSignActivity.class);
                        intent.putExtra("group_id", mGroupId);
                        intent.putExtra("form_id", mFormId);
                        intent.putExtra("addressData", mAddressDatas.get(position));
                        startActivity(intent);
                        finish();
                    } else {
                        Intent result = new Intent();
                        result.putExtra("addressData", mAddressDatas.get(position));
                        setResult(RESULT_OK, result);
                        finish();
                    }
                }
            }
        });
        mTvCancle.setOnClickListener(this);

        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(LegworkMapSearchActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    if (!StringUtil.isEmpty(mEtSearch.getText().toString().trim())) {
                        waitDlgShow();
                        searchText=mEtSearch.getText().toString().trim();
                        pageIndex=1;
                        mAddressDatas.clear();
                        searchNeayBy(searchText);
                    }
                    return true;
                }
                return false;
            }
        });

    }

    private void getIntentData() {
        Intent intent = getIntent();
        mLatitude = intent.getDoubleExtra("latitude", 0);
        mLongitude = intent.getDoubleExtra("longitude", 0);
        mGroupId = intent.getStringExtra("group_id");
        mFormId = intent.getStringExtra("form_id");
            flag = intent.getIntExtra("flag",0);
    }


    private void searchNeayBy(String text) {
        PoiNearbySearchOption option = new PoiNearbySearchOption();
        //option.keyword(address);
        option.keyword(text);
        option.sortType(PoiSortType.distance_from_near_to_far);
        option.location(new LatLng(mLatitude, mLongitude));
        /*if (radius != 0) {
            option.radius(radius);
        } else {*/
            option.radius(500);
        /*}*/
        option.pageNum(pageIndex);
        option.pageCapacity(pageSize);
        mPoiSearch.searchNearby(option);

    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if (poiResult == null
                || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            showFooterLayout(false);
            Toast.makeText(LegworkMapSearchActivity.this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            mAddressDatas.clear();
            mAdapter.bindData(mAddressDatas);
            waitDlgDismiss();
            return;
        }
        if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {

            if (poiResult.getAllPoi() != null && poiResult.getAllPoi().size() > 0) {
                if (poiResult.getAllPoi() != null && poiResult.getAllPoi().size() > 0) {
                    for (int i = 0; i < poiResult.getAllPoi().size(); i++) {
                        count=poiResult.getAllPoi().size();
                        PoiInfo info = poiResult.getAllPoi().get(i);
                        AddressData addressData = new AddressData();
                        addressData.setCity(info.city);
                        addressData.setName(info.name);
                        addressData.setAddress(info.address);
                        addressData.setLatitude(info.location.latitude);
                        addressData.setLongitude(info.location.longitude);
                        addressData.setUid(info.uid);
                        if (getDistance(info.location.latitude, info.location.longitude) <= 500) {
                            mAddressDatas.add(addressData);
                        }
                    }
                    if (mAddressDatas.size() > 0) {
                        mAdapter.bindData(mAddressDatas);
                    } else {
                        mAddressDatas.clear();
                        mAdapter.bindData(mAddressDatas);
                        showFooterLayout(false);
                        Toast.makeText(LegworkMapSearchActivity.this, "未找到结果", Toast.LENGTH_LONG)
                                .show();
                    }

                    waitDlgDismiss();
                }
                /*Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);*/
            }

            return;
        }
        if (poiResult.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : poiResult.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            Toast.makeText(LegworkMapSearchActivity.this, strInfo, Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(LegworkMapSearchActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(LegworkMapSearchActivity.this, poiDetailResult.getName() + ": " + poiDetailResult.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPoiSearch.destroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_map_search_input_cancle:
                finish();
                break;
        }
    }

    private void waitDlgShow() {
        if (mProgressDialog == null) {
            mProgressDialog = AllDialogUtil.getInstance(this).waitDialog("请稍后");
//            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }

    }

    private void waitDlgDismiss() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    /**
     * 获取两点距离
     *
     * @param latitude
     * @param longitude
     * @return
     */
    private double getDistance(double latitude, double longitude) {
        LatLng start = new LatLng(latitude, longitude);
        LatLng end = new LatLng(mLatitude, mLongitude);
        //  DecimalFormat df = new DecimalFormat("#.0");//保留1位小数
        //return df.format(DistanceUtil.getDistance(start, end) * 1000) + "";
        Log.i(Tag, "签到经纬度 latitude:" + latitude + "---" + "longitude:" + longitude);
        Log.i(Tag, "定位经纬度 latitude:" + mLatitude + "---" + "longitude:" + mLongitude);
        Log.i(Tag, "距离 distance:" + DistanceUtil.getDistance(start, end));
        //return String.valueOf(DistanceUtil.getDistance(start, end)).split("\\.")[0];
        return DistanceUtil.getDistance(start, end);
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        switch (absListView.getId()) {
            case R.id.lv_baidu_map_search_list:
                if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
                    if (is_scrolling) {
                        if (count < pageSize) {
                            showFooterLayout(false);
                        } else {
                            ++pageIndex;
                            searchNeayBy(searchText);
                        }
                    }
                }
                break;
        }

    }

    @Override
    public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        switch (absListView.getId()) {
            case R.id.lv_baidu_map_search_list:
                if ((firstVisibleItem + visibleItemCount == totalItemCount) && totalItemCount != 0) {
                    if (count < pageSize) {
                        showFooterLayout(false);
                    } else {
                        showFooterLayout(true);
                    }
                    is_scrolling = true;
                } else {
                    is_scrolling = false;
                }
                break;
        }

    }
    public void showFooterLayout(boolean isShow) {
        if (isShow) {
            mFooterLayout.setVisibility(View.VISIBLE);
            mFooterText.setText(this.getResources().getString(
                    R.string.xlistview_footer_hint_normal));
            mFooterProgress.setVisibility(View.VISIBLE);
        } else {
            mFooterLayout.setVisibility(View.GONE);

        }
    }

}
